package com.lntea.netty.demo.diff.echo.bio;

import java.io.*;
import java.net.Socket;
import java.util.Calendar;

/**
 * Title: BioEchoServerHandler.java<br>
 * Description:  阻塞类型服务端处理器<br>
 * Copyright: Copyright (c) 2015<br>
 * Company: 北京云杉世界信息技术有限公司<br>
 *
 * @author lichao
 * @date 2019/11/4 12:01
 */
public class BioEchoServerHandler implements Runnable {
    /** 查询时间约定字符串 */
    private String echoStr;
    /** server accept socket */
    private Socket socket;

    public BioEchoServerHandler(Socket socket, String echoStr) {
        this.socket = socket;
        this.echoStr = echoStr;
    }

    @Override
    public void run() {
        try (BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter outputWriter = new PrintWriter(socket.getOutputStream(), true)) {
            while(true) {
                String body = inputReader.readLine();
                if (body == null || body.equals("")) {
                    break;
                }
                System.out.println(String.format("Echo Server receive msg: %s", body));
                if (echoStr.equals(body)) {
                    String curTime = Calendar.getInstance().getTime().toString();
                    outputWriter.println(curTime);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
